package com.mxchip.livestar.ui.recentcall

import android.content.DialogInterface
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.mxchip.livestar.CallActivityA
import com.mxchip.livestar.R
import com.mxchip.livestar.base.CallLogViewModel
import com.mxchip.livestar.base.RecentCallBean
import com.mxchip.livestar.base.toast
import com.mxchip.livestar.repository.RoomClientRepository
import com.mxchip.livestar.ui.GroupCall
import com.mxchip.livestar.ui.P2PSingleCall
import kotlinx.android.synthetic.main.fragment_recent_call.*

class RecentCallFragment : Fragment() {

    private val callLogViewModel by viewModels<CallLogViewModel>()

    private val adapter: RecentCallAdapter by lazy {
        RecentCallAdapter(onClickListener = this::onItemClick)
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        val view = inflater.inflate(R.layout.fragment_recent_call, container, false)

        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recycler_view.setLayoutManager(LinearLayoutManager(context))
        recycler_view.adapter = adapter
        recycler_view.showEmpty()

        callLogViewModel.callLogAll.observe(viewLifecycleOwner, Observer { list ->
            adapter.data = list
            adapter.notifyDataSetChanged()
        })
    }

    private fun onItemClick(view: View, bean: RecentCallBean) {
        val callDialog = RecentCallDialog(requireContext())
        callDialog.setBean(bean)
        callDialog.setOnClickListener { dialog: DialogInterface, which: Int ->
            Log.e(TAG, "which: $which")
            when (which) {
                0 -> {
                    val number = bean.number
                    makeCall(number)
                }
                1 -> {
                    val number = bean.number
                    addContact(number)
                }
                2 -> {
                    val id = bean.id
                    callLogViewModel.deleteCallLogById(id!!)
                }
            }
            dialog.dismiss()
        }
        callDialog.setOnDismissListener { dialog: DialogInterface -> (dialog as RecentCallDialog).setOnClickListener(null) }
        callDialog.show()
    }

    private fun addContact(number: String?) {
        val action = RecentCallFragmentDirections.actionRecentCallFragmentToAddMemberFragment()

        action.number = number

        findNavController().navigate(action)
    }

    private fun makeCall(number: String?) {
        if (activity != null && !RoomClientRepository.connected()) {
            toast("网络未连接，暂时无法呼叫")
            return
        }
        try {
            val callNumber: String = number!!
            val call = callLogViewModel.makeCall(callNumber)
            val callString = when (call) {
                is P2PSingleCall ->
                    call.number
                is GroupCall ->
                    call.groupNumber

                else ->
                    throw IllegalStateException("call is Unknow type")
            }
            callLogViewModel.createCallLog(callString, "2")
            // val strings = arrayOf(callNumber.trim())
//        val call = if (callNumber.length != 12) {
//            P2PSingleCall(callNumber)
//        } else {
//            GroupCall(number)
//        }
            context?.let { CallActivityA.open(it, call) }
        } catch (t: Throwable) {
            t.message?.let { toast(it) }
        }
    }

    companion object {
        private const val TAG = "RecentCallFragment"
    }
}